package com.hejia.bulbul.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hejia.alauda.entity.Message;
import com.hejia.alauda.entity.User;
import com.hejia.alauda.entity.example.MessageExample;
import com.hejia.alauda.service.MessageService;
import com.hejia.alauda.service.UserService;
import com.hejia.alauda.utils.Pager;
import com.hejia.bulbul.entity.DataTablesReturnObject;
import com.hejia.bulbul.entity.JSONParam;

/**
 * 
 * 个人消息
 *
 *
 * Created by showone on 2014 上午11:19:18.
 *
 * @Copyright: 2014 www.hejiajinrong.com All rights reserved.
 */

@Controller
@RequestMapping("personMessage")
public class PersonMessageController extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private MessageService messageService;

	/**
	 *
	 * @param pager
	 *            分页信息
	 * @param model
	 *            设置参数的model
	 * @return list页面
	 */
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Model model) {
		return "/message/personList";
	}

	/**
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add(ModelMap model) {
		return "/message/personAdd";
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String add(ModelMap model, 
			RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> items = upload.parseRequest(request);
			String title = null;
			String url = null;
			String content = null;
			String mobiles = null;
			String category = null;
			String openAppPage = null;
			InputStream is = null;
			int success = 0;
			for (FileItem item : items) {
				if (item.isFormField()) {
					if ("title".equals(item.getFieldName())) {
						title = item.getString("utf-8");
					} else if ("url".equals(item.getFieldName())) {
						url = item.getString("utf-8");
					} else if ("content".equals(item.getFieldName())) {
						content = item.getString("utf-8");
					} else if ("mobiles".equals(item.getFieldName())) {
						mobiles = item.getString("utf-8");
					} else if ("category".equals(item.getFieldName())) {
						category = item.getString("utf-8");
					} else if ("openAppPage".equals(item.getFieldName())) {
						openAppPage = item.getString("utf-8");
					}
				} else {
					is = item.getInputStream();
				}
			}
			BufferedReader dr = new BufferedReader(new InputStreamReader(is));
			String mobile = "";
			while (mobile != null) {
				mobile = dr.readLine();
				if (mobile == null) {
					break;
				}
				System.out.println(mobile);
				User user = userService.findUserByMobile(mobile);
				if (user != null) {
					if (messageService.sendAppMessage(
							user, category,
							title, content, 
							url, openAppPage)) {
						success++;
					}
				}
			}
			dr.close();
			is.close();
			if (mobiles != null) {
				String[] arrMobile = mobiles.split(",");
				for (int i = 0; arrMobile != null && i < arrMobile.length; i++) {
					User user = userService.findUserByMobile(arrMobile[i]);
					if (user != null) {
						if (messageService.sendAppMessage(
								user, category,
								title, content, 
								url, openAppPage)) {
							success++;
						}
					}
				}
			}
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", success + "条个人消息添加成功");
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/personMessage/list";
	}

	/**
	 * 系统消息删除
	 *
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		if (messageService.deletePersonMessage(id)) {
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", "个人消息删除成功");
		} else {
			redirectAttributes.addFlashAttribute("status", STATUS_FAILD);
			redirectAttributes.addFlashAttribute("msg", "个人消息删除失败");
		}

		return "redirect:/personMessage/list";
	}
	

//	/**
//	 * 消息修改页面
//	 *
//	 * @param id
//	 * @param model
//	 * @return
//	 */
//	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
//	public String show(@PathVariable Long id, ModelMap model) {
//		SystemMessage msg = messageService.getSystemMessage(id);
//		model.put("message", msg);
//
//		return "/message/personAdd";
//	}
//
//	/**
//	 * 系统消息修改提交
//	 *
//	 * @param msg
//	 * @param model
//	 * @param redirectAttributes
//	 * @return
//	 */
//	@RequestMapping(value = "update", method = RequestMethod.POST)
//	public String update(SystemMessage msg, ModelMap model,
//			RedirectAttributes redirectAttributes) {
//		SystemMessage oldMsg = messageService.getSystemMessage(msg.getId());
//		oldMsg.setContent(msg.getContent());
//		oldMsg.setTitle(msg.getTitle());
//		oldMsg.setDeadline(msg.getDeadline());
//
//		if (messageService.updateSystemMessage(oldMsg)) {
//			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
//			redirectAttributes.addFlashAttribute("msg", "系统消息修改成功");
//		} else {
//			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
//			redirectAttributes.addFlashAttribute("msg", "系统消息修改失败");
//		}
//		return "redirect:/message/personList";
//	}
	

	/**
	 * 以ajax格式返回列表请求
	 *
	 * @param params
	 * @return
	 */

	@RequestMapping(value = "listAsAjax", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesReturnObject<Message> listAsAjax(
			@RequestBody JSONParam[] params) {
		HashMap<String, String> paramMap = JSONParam.convertToMap(params);

		// 分页信息
		Pager<Message> pager = new Pager<Message>();
		int start = Integer.parseInt(paramMap.get("iDisplayStart"));
		int length = Integer.parseInt(paramMap.get("iDisplayLength"));
		pager.setPageSize(length);
		pager.setPageNumber(start / length + 1);

		// 查询条件
		MessageExample exp = new MessageExample();

		String sSearch = paramMap.get("sSearch");
		if (StringUtils.isNotEmpty(sSearch)) {
			exp.appendCriterion("content like  ", "%" + sSearch + "%");
		}
		// 排序
		int iSortingCols = Integer.parseInt(paramMap.get("iSortingCols"));
		for (int i = 0; i < iSortingCols; i++) {
			String iSortCol = paramMap.get("iSortCol_" + i);
			String mDataProp = paramMap.get("mDataProp_" + iSortCol);
			String sSortDir = paramMap.get("sSortDir_" + i);
			if (i > 0) {
				exp.setOrderByClause(exp.getOrderByClause() + ",");
				exp.setOrderByClause(exp.getOrderByClause() + mDataProp + " "
						+ sSortDir);
			} else {
				exp.setOrderByClause(mDataProp + " " + sSortDir);
			}
		}

		pager = messageService.findMessage(exp, pager);

		DataTablesReturnObject<Message> dtr = new DataTablesReturnObject<Message>(
				pager.getTotalCount(), paramMap.get("sEcho"), pager.getList());
		return dtr;
	}

}
